package com.prb.controller;

import com.prb.service.ResumeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/login")
public class LoginController {

    String name = "admin";
    String pwd = "admin";


    @Autowired
    ResumeService resumeService;

    @RequestMapping("/page")
    public String login(){

        System.out.println("login page");
        return "login";
    }

    @PostMapping("/do")
    public void doLogin(HttpServletRequest request , HttpServletResponse response , String userName , String password) throws IOException, ServletException {


        //登录失败页面
        String resultPage = "/login/page";

        if (name.equals(userName) && pwd.equals(password)) {
            //登录成功，跳转到 简历列表
            String token = UUID.randomUUID().toString();
            //response.setHeader("token" , token);
            Cookie cookie = new Cookie("token" , token);
            cookie.setPath("/");
            response.addCookie(cookie);

            request.getSession().setAttribute("token" , token);

            resultPage = "/resume/page";
        }

        response.sendRedirect(resultPage);
    }


    @GetMapping("/logout")
    public void logout(HttpServletRequest request , HttpServletResponse response ) throws ServletException, IOException {

        request.getSession().setAttribute("token" , null);
        //response.setHeader("token" , null);
        Cookie cookie = new Cookie("token" , null);
        cookie.setPath("/");
        response.addCookie(cookie);

        request.getRequestDispatcher("/login/page").forward(request , response);

    }

}
